package com.edou.member.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.edou.base.constant.SessionConstant;
import com.edou.base.util.EncryptUtil;
import com.edou.member.controller.member.MemberUserLoginController;
import com.edou.member.entity.MemberUser;
import com.edou.member.service.IMemberUserService;

/**
 * 会员登录拦截器
 * @creator     admin
 * @create-time Jun 19, 2015   2:09:07 PM
 * @version 1.0
 */
public class MemberLoginInterceptor extends HandlerInterceptorAdapter {
	
	@Resource
	private IMemberUserService memberUserService;
	
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		
		HttpSession session = request.getSession();
		
		//自动登录 - 通过Cookie中的Identity值进行判断
		this.isAutoLoginByCookieIdentity(request);
		
		//判断用户是否登录
		MemberUser member = (MemberUser)session.getAttribute(SessionConstant.CURRENT_MEMBER);
		if(null == member){
			//判断请求方式
			String requestType = request.getHeader("X-Requested-With");
			if(StringUtils.isNotBlank(requestType) && StringUtils.equals("XMLHttpRequest", requestType)){
				//异步请求
				response.setContentType("text/json;charset=UTF-8");
				response.getWriter().write("{\"status\":\"noLogin\",\"message\":\"请登录\"}");
				return false;
			}
			
			String preUrl = request.getHeader("Referer");
			
			// 获得请求URL
			request.setAttribute("preUrl", preUrl);
			if (null != request.getQueryString()){
                session.setAttribute("preUrl", request.getRequestURL().append("?").append(request.getQueryString()).toString());
			}else{
                session.setAttribute("preUrl", request.getRequestURL().toString());
			}
			request.getRequestDispatcher("/member/login.htm").forward(request, response); 
			
			return false;
		}else{
			
			
		}
		
		return super.preHandle(request, response, handler);
	}
	

	/**
	 * 自动登录 - 通过Cookie中的Identity值进行判断
	 * @param request
	 * @param response
	 * @param handler
	 * @throws Exception
	 */
	protected void isAutoLoginByCookieIdentity(HttpServletRequest request){
		HttpSession session = request.getSession();
		// 会员自动登录
		Cookie cookies[] = request.getCookies();
		if (cookies != null) {
			//遍历Cookies
			for (Cookie cookie : cookies) {
				if (MemberUserLoginController.MEMBER_AUTOLOGIN.equals(cookie.getName())) {
					//取的对应Cookie 进行解密
					String decrypt = EncryptUtil.decrypt(cookie.getValue());
					//根据解密后获得ID去数据库中查询
					MemberUser member = memberUserService.getMemberUserById(decrypt);
					if(member != null){
						session.setAttribute(SessionConstant.CURRENT_MEMBER, member);
					}
				}
			}
		}
	}
	
	
}
